#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main()
{
	int shmid;
	int proj_id;
	key_t key;
	int size;
	char *addr;
	pid_t pid;
	key=IPC_PRIVATE;	/*for here , 'key' equal 'IPC_PRIVATE' so the following function in 'shmget(key,size,shflg)', here shmflg should replace by 'IPC_CREAT'*/
	shmid=shmget(key,1024,IPC_CREAT|0660);	/*创建共享内存 if the value 'key' not equal 'IPC_PRUVATE' and 'shmflg' equal 'IPC_CREAT' then this function will open the area that definted by the value 'key' ****** to get more , man 2 shmget ******/
	if(shmid==-1)
	{
		perror("creat share memory failed !\n");
		return 1;
	}
	addr=(char *)shmat(shmid,NULL,0);	/* shmat means : share memory attach , use to attach the share memory area to definted process address space , here 'NULL' means to open a memory space by system defult,'0'表示操作方式(what ? Google it !) */
			if(addr==(char *)(-1))
			{
				perror("cannot attach !\n");
				return 1;
			}
			printf("share memory segment's address:%x\n",addr);
			strcpy(addr,"welcome to openSuSE!\n");
			pid=fork();
			if(pid==-1)
			{
				perror("creat new process failed !\n");
				return 1;
			}
			else if(pid==0)
			{
				printf("child process string is '%s'\n",addr);
				_exit(0);
			}
			else
			{
				wait(NULL);
				printf("parent process string is '%s'\n",addr);
				if(shmdt(addr)==-1)	/* shmdt use to separate the attached share memory space , if failed return -1 */
				{
					perror("release memory failed !\n");
					return 1;
				}
				if(shmctl(shmid,IPC_RMID,NULL)==-1)	/* shmctl means : share memory contrl. shmctl(int shmid,int command,strcut shmid_ds *buf), to learn more , refer to man shmctl */
				{
					perror("FAILED!!!\n");
					return 1;
				}
			}
			return 0;
}
